package org.skatiger.jrove.component.foreach;

import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

public abstract class ForeachUtil {
    private ForeachUtil() {
    }

    public static ForeachStatusIterator iterate(Object obj, Integer begin,
            Integer end, Integer step) {
        if (obj != null) {
            Class<?> targetClass = obj.getClass();
            if (Iterator.class.isAssignableFrom(targetClass)) {
                return new ForeachStatusIteratorImpl((Iterator<?>) obj, begin,
                        end, step);
            } else if (Collection.class.isAssignableFrom(targetClass)) {
                return new CollectionIterator((Collection<?>) obj, begin, end,
                        step);
            } else if (targetClass.isArray()) {
                return new ArrayIterator((Object[]) obj, begin, end, step);
            } else if (Map.class.isAssignableFrom(targetClass)) {
                return new MapIterator((Map<?, ?>) obj, begin, end, step);
            } else if (Enumeration.class.isAssignableFrom(targetClass)) {
                return new EnumerationIterator((Enumeration<?>) obj, begin,
                        end, step);
            } else {
                return new CollectionIterator(Collections.singleton(obj),
                        begin, end, step);
            }
        }
        return NULL_FOREACH_ITERATOR;
    }

    public static final ForeachStatusIterator NULL_FOREACH_ITERATOR = new ForeachStatusIteratorImpl(
            Collections.emptyList().iterator(), null, null, null);
}
